package com.lazy.demo1.handler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lazy.lib.util.DataQueue;
import com.lazy.localfs.LocalFsMgr;
import com.lazy.netty.ex.bench.server.BenchServerHandler;

/**
 * 消费任务
 * @author luodan
 */
public class GidConsumeTask implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(GidConsumeTask.class);
    protected DataQueue<String> dataQueue;
    
    public GidConsumeTask(DataQueue<String> dataQueue){
        this.dataQueue = dataQueue;
    }
    
    @Override
    public void run(){
        // 
        List<String> list = new ArrayList<String>(1000);
        if (dataQueue.size() > 0) {
            list.clear();
            int count = dataQueue.drainTo(list, 5000);
            if (count == 0) {
                return;
            }
            String filePath = LocalFsMgr.getInstance().getCurFilePath();
            BufferedOutputStream out = null;
            try {
                File file = new File(filePath);
                if(!file.exists()) {
                    file.createNewFile();
                }
                out=new BufferedOutputStream(new FileOutputStream(file));
                // write 1M file
                for (String str : list) {
                    writeData(out, str);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try{
                        out.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
            
            // removed oldest files
            LocalFsMgr.getInstance().removeOldestDir(10);
        }
    }
    
    public void writeData(OutputStream out, String str) {
        try{
            byte[] bin = str.getBytes("UTF8");
            out.write(bin);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}
